<?php
namespace slinks\extensions\onecms\cms\joomla;

use slinks\core\DependencyInjection\ContainerInterface;
use slinks\common\util\StringUtil;
use slinks\core\dependencyInjectionExt\ContainerConstants;
use slinks\extensions\action\routing\RouterInterface;

/**
 * Provides a single entry point to work with Joomla core plugins to allow routing to work with SlinksActions
 *
 * @author navid
 * @Service('joomla.router.helper')
 */
class JoomlaRouterHelper {
   
    private $container;
    
    private $router;
    
    /**
     * @param ContainerInterface $container 
     * @Inject
     */
    public function __construct(ContainerInterface $container,RouterInterface $router) {
        $this->container = $container;
        $this->router = $router;
    }
    
    
    /**
     * Parses the given slinks route and adds needed joomla component information.
     * This will be called by the joomla custom Routing functions.
     * @param type $router
     * @param type $uri 
     */
    public function parseRoute(&$router, &$uri){
        $ret =array();
        foreach($this->container->getParameter(ContainerConstants::PARAM_APPLICATIONS) as $application){
            if(StringUtil::beginsWith($uri->getPath(), $application)){
               $ret['option'] = 'com_'.$application;
               // remove appplication from url 
               // first make valid reg expression.
               $origPathInfoReg = '/'.str_replace('/','\/',$_SERVER['PATH_INFO']).'/';
               $_SERVER['PATH_INFO'] = preg_replace('/\/'.$application.'/','', $_SERVER['PATH_INFO']);   
               $_SERVER['REQUEST_URI'] = preg_replace($origPathInfoReg,$_SERVER['PATH_INFO'], $_SERVER['REQUEST_URI']);
               $_SERVER['PATH_TRANSLATED'] = preg_replace($origPathInfoReg,$_SERVER['PATH_INFO'], $_SERVER['PATH_TRANSLATED']);
               $_SERVER['PHP_SELF'] = preg_replace($origPathInfoReg,$_SERVER['PATH_INFO'], $_SERVER['PHP_SELF']);
               $_REQUEST['PATH_MODIFIED'] = true; // tell slinks joomla components to ignore other view values
               break;
            }
        }
        return $ret;
    }
    
}
